<template>
  <div id="map-container" ref="mapContainer"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import 'leaflet.chinatmsproviders' // leaflet 国内地图瓦片快速访问api支持
import 'leaflet-ant-path';
import 'leaflet-polylinedecorator'

const props = defineProps({
  initialPath: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['path-updated']);

const TIAN_DI_TU_KEY = "2701ac457d958d61ad7cb6e2f9cddd29"
const mapContainer = ref(null);
let map = null;
let pathLayer = null;
let markersLayer = null;
let isEditing = ref(false);
let gPath = null;
let isShowArrow = false;
let arrow = null;
let arrowPolylineDecorator = null;
// 初始化地图
onMounted(() => {
  if (mapContainer.value) {
    map = L.map(mapContainer.value).setView([29.55551542, 106.56525968], 13);
    
  // 天地图普通
  L.tileLayer.chinaProvider('TianDiTu.Normal.Map',{maxZoom:18,minZoom:5, key: TIAN_DI_TU_KEY}).addTo(map);
  // 天地图标注
  L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion',{maxZoom:18,minZoom:5, key: TIAN_DI_TU_KEY}).addTo(map);

    // 初始化路径图层
    pathLayer = L.layerGroup().addTo(map);
    markersLayer = L.layerGroup().addTo(map);
    
    // 绘制初始路径
    drawPath(props.initialPath);
    
    // 启用编辑
    toggleEditing(true);

    startAnimation();
  }
});

let repeat = 5;
function startAnimation() { 
  if (isShowArrow && arrow) {
    if (arrowPolylineDecorator) {
      var patterns = arrowPolylineDecorator.options.patterns;
      var currentOffset = parseFloat(patterns[0].offset);
      // 更新偏移量（5%增量）
      var newOffset = (currentOffset + 0.04) % repeat;
      patterns[0].offset = newOffset + '%';
      // 重新设置装饰器
      arrowPolylineDecorator.setPatterns(patterns);
    }
  }
  requestAnimationFrame(startAnimation)
}

// 绘制路径和标记点
const drawPath = (coordinates) => {
  if (!map) return;
  
  // 清除现有路径和标记
  pathLayer.clearLayers();
  markersLayer.clearLayers();

  if (coordinates && coordinates.length > 0) {
    // 创建路径线
  var antPath = L.polyline.antPath;
  gPath = antPath(coordinates, {
        "paused": false,   　　//暂停  初始化状态
        "reverse": false,　　//方向反转
        "delay": 500,　　　　//延迟，数值越大效果越缓慢
        "dashArray": [10, 10],　//间隔样式
        "weight": 5,　　　　//线宽
        "opacity": 1,　　//透明度
        "color": "#FFFFFF00",　//颜色
        "pulseColor": "#f00"　　//块颜色
    });
  if (!isShowArrow) {
    gPath.addTo(pathLayer);
  } else {
    arrow = L.polyline(coordinates, {
      color: '#f00',
      weight: 7,
      opacity: 1
    }).addTo(pathLayer);
    repeat = 20 / coordinates.length - 1;

    arrowPolylineDecorator = L.polylineDecorator(arrow, {
        patterns: [
          {
            // 模式符号的偏移位置
            offset: '0%',
            // 模式符号的重复间隔
            repeat: `${repeat}%`,
            // 符号实例
            symbol: L.Symbol.arrowHead({
              // 符号大小
              pixelSize: 5,
              polygon: false,
              // 符号样式
              pathOptions: {
                // 是否显示边线
                stroke: true,
                weight: 2,
                color: '#fff'
              }
            })
          }
        ]
    })
    .addTo(pathLayer)
  }

    // 创建可拖动的标记点
    coordinates.forEach((coord, index) => {
      const marker = L.marker(coord, {
        draggable: true,
        icon: L.divIcon({
          className: 'path-marker',
          html: `<div>${index + 1}</div>`,
          iconSize: [24, 24]
        })
      }).addTo(markersLayer);
      
      // 标记点拖动事件
      marker.on('dragend', (e) => {
        const newPos = e.target.getLatLng();
        coordinates[index] = [newPos.lat, newPos.lng];
        updatePath(coordinates);
      });
      
      // 标记点点击事件（删除点）
      marker.on('click', (e) => {
        if (e.originalEvent.ctrlKey || e.originalEvent.metaKey) {
          coordinates.splice(index, 1);
          updatePath(coordinates);
        }
      });
    });

    // 调整视图以适应路径
    // 聚焦路径
    // map.fitBounds(gPath.getBounds());
  }
};

// 更新路径并触发事件
const updatePath = (coordinates) => {
  drawPath(coordinates);
  emit('path-updated', coordinates);
};

// 切换编辑模式
const toggleEditing = (enable) => {
  isEditing.value = enable;
  
  if (enable) {
    // 添加地图点击事件来新增点
    map.on('click', addNewPoint);
  } else {
    // 移除地图点击事件
    map.off('click', addNewPoint);
  }
};

// 添加新点
const addNewPoint = (e) => {
  const currentPath = pathLayer.getLayers()[0]?.getLatLngs() || [];
  const newPath = [...currentPath.map(ll => [ll.lat, ll.lng]), [e.latlng.lat, e.latlng.lng]];
  updatePath(newPath);
};

function focusLine() {
   if (gPath) {
  map.fitBounds(gPath.getBounds());
  }
}


function turnDir() {
  if (gPath) { // 路径存在才能反转，反转逻辑可以使用ant插件实现，也可以直接将点位倒叙重新渲染即可，这里采用的是重新渲染
    updatePath(pathLayer.getLayers()[0]?.getLatLngs().reverse());
  }
}

function toggleArrow(_isShowArrow) {
  if (gPath) {
    isShowArrow = _isShowArrow;
    updatePath(pathLayer.getLayers()[0]?.getLatLngs());
  }
}

// 清理地图
onBeforeUnmount(() => {
  if (map) {
    map.off('click', addNewPoint);
    map.remove();
    map = null;
  }
});

// 暴露方法给父组件
defineExpose({
  toggleEditing,
  updatePath,
  turnDir,
  focusLine,
  toggleArrow,
  getCurrentPath: () => pathLayer.getLayers()[0]?.getLatLngs() || []
});
</script>

<style scoped>
#map-container {
  width: 100%;
  height: 500px;
  z-index: 1;
}

/* 修复 Leaflet 默认图标路径问题 */
:deep(.leaflet-marker-icon),
:deep(.leaflet-marker-shadow) {
  filter: none !important;
}

/* 自定义标记点样式 */
:deep(.path-marker) {
  background: #ff0000;
  color: white;
  border-radius: 50%;
  text-align: center;
  line-height: 24px;
  font-weight: bold;
  font-size: 12px;
  border: 2px solid white;
  box-shadow: 0 0 5px rgba(0,0,0,0.5);
}
</style>
